package util;

import org.xml.sax.SAXException;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBException;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class JAXBUtil
{
    public static final String tmpFile = "data.xml";
    public static final File tmp = new File(tmpFile);

    public static void saveXmlToFile(Object object, String path, String defaultNameSpace) throws JAXBException, IOException
    {
        //        JAXBContext context = JAXBContext.newInstance(aClass);
        //        Marshaller marshaller = context.createMarshaller();
        //        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //        OutputFormat xmlFormat = OutputFormat.createPrettyPrint();
        //        xmlFormat.setEncoding("utf-8");
        //        xmlFormat.setIndent(true);
        //        XMLWriter writer = new XMLWriter(new FileOutputStream(path), xmlFormat);
        //        XMLFilterImpl filter = new MyXMLWriter(defaultNameSpace);
        //        filter.setContentHandler(writer);
        //        marshaller.marshal(object, filter);
        JAXB.marshal(object, tmp);
        replaceStringInFile(tmpFile, "xmlns:" + defaultNameSpace, "", path);

    }

    public static <T> T parseXmlFromFile(String path, Class <T> tClass, String defaultNameSpace) throws JAXBException, SAXException, IOException, XMLStreamException
    {
        replaceStringInFile(path, "xmlns=", "xmlns:" + defaultNameSpace + "=", tmpFile);
        return JAXB.unmarshal(tmp, tClass);
    }

    private static void replaceStringInFile(String sourcePath, String sourceString, String targetString, String targetPath) throws IOException
    {
        List <String> lines = FileUtils.readFileContent(sourcePath);
        StringBuilder builder = new StringBuilder();
        lines.forEach(line -> builder.append(line).append("\n"));
        String content = builder.toString();
        content = content.replace(sourceString, targetString);
        FileOutputStream outputStream = new FileOutputStream(targetPath);
        outputStream.write(content.getBytes());
        outputStream.close();
    }

}
